package com.guigu.eduservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.R;
import com.guigu.eduservice.dto.UserDto;
import com.guigu.eduservice.entity.User;
import com.guigu.eduservice.service.UserService;
import com.guigu.eduservice.utils.JwtUtils;
import com.guigu.eduservice.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;



/**
 * <p>
 * 用户表（平台买卖双方用户） 前端控制器
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/eduservice/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @GetMapping("/getAll")
    public List<User> getAll() {
        return userService.list();
    }

    @PostMapping("/getUserPage/{pageNum}/{pageSize}")
    public PageInfo<User> getUserAll(@RequestBody UserVo vo,@PathVariable("pageNum") Integer pageNum,@PathVariable("pageSize") Integer pageSize) {
        return userService.getUserAll(vo,pageNum,pageSize);
    }
    //李xx
    //登录(密码为加密)
        @PostMapping("Login")
    public R Login(@RequestBody UserDto userDto) {
        String login = userService.login(userDto);
        System.out.println("token:"+ login);
        return R.ok().data("token", login);
    }
    //登录信息
    @PostMapping("/loginInfo")
    public R loginInfo(HttpServletRequest request) {
        System.out.println("登录信息");
        System.out.println(request);
        // 解析请求对象（从请求对象的头部取出token）
        String name = JwtUtils.getUserNameByJwtToken(request);
        int id =JwtUtils.getUserIDByJwtToken(request);
        User user=new User();
        user.setUserName(name);
        user.setUserId((long) id);
        System.out.println("name:"+user);
        return R.ok().data("name", user);
    }
    //根据HttpServletRequest里面的用户ID拿到用户
    @PostMapping("/Myzhongxin")
    public R Myzhongxin(HttpServletRequest request) {
        // 解析请求对象（从请求对象的头部取出token）
        int id =JwtUtils.getUserIDByJwtToken(request);
        if (id !=0 ){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getUserId, id);
            User user = userService.getById(id);
            return R.ok().data("user", user);
        }
        return R.ok().data("user", null);
    }

    // 处理前端部分更新请求（用户修改个人信息）
    @PostMapping("/updateInfo")
    public R updateUserInfo(HttpServletRequest request,@RequestBody User user) {
        // 1. 验证用户ID是否存在（确保更新的是指定用户）
        int id =JwtUtils.getUserIDByJwtToken(request);
        if (id == 0) {
            return R.error().message("用户ID不能为空");
        }

        // 2. 使用UpdateWrapper构造更新条件，只设置非null字段
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",id); // 必须指定更新的用户ID

        // 3. 逐个判断前端传递的字段，非null则加入更新
        if (user.getUserName() != null) {
            updateWrapper.set("user_name", user.getUserName());
        }
        if (user.getPhone() != null) {
            updateWrapper.set("phone", user.getPhone());
        }
        if (user.getIdCard() != null) {
            updateWrapper.set("id_card", user.getIdCard());
        }
        if (user.getAvatar() != null){
            updateWrapper.set("avatar", user.getAvatar());
        }
        // 其他需要更新的字段

        // 4. 执行更新
        boolean success = userService.update(updateWrapper);
        if (success) {
            return R.ok().message("更新成功");
        } else {
            return R.error().message("更新失败");
        }
    }
    @GetMapping("/getByPhone/{phone}/{password}")
    public User getByPhone(@PathVariable String phone,@PathVariable String password) {
        System.out.println(phone);
        System.out.println(password);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        QueryWrapper<User> wrapper = userQueryWrapper.eq("phone", phone);
        User user = userService.getOne(wrapper);

        System.out.println("11"+user);

       return user;
    }

//        修改用户名称和手机号
    @PostMapping("/updateUser")
    public R updateUser(@RequestBody User user) {
        System.out.println("修改用户信息："+user);
        boolean update = userService.updateById(user);
        if (update) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @PostMapping("/sendCode")
    public R sendCode(@RequestBody Map<String,String> params){
        String phone = params.get("phone");
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        log.warn("发送短信：{}", phone, code);
        // 存 Redis 5 分钟
        stringRedisTemplate.opsForValue().set("sms:code:" + phone, code, Duration.ofMinutes(5));
        // TODO 调用腾讯云/阿里云短信 SDK 下发 code
        System.out.println("验证码"+code);
        return R.ok().data("code", code);
    }


    @PostMapping("/register")
    public R register(@RequestBody User user) {



        String cacheCode = stringRedisTemplate.opsForValue().get("sms:code:" + user.getPhone());
        System.out.println("BBB："+user);
        if(cacheCode  == null || !cacheCode.equals(user.getCode())) {
            return R.error().message("验证码错误");
        }

        System.out.println("ccc："+user);
        String phone = user.getPhone();
        String password = user.getPassword();
        // 1. 简单校验
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            return R.error();
        }


        System.out.println("AAA");

        // 2. 是否已存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        if (userService.count(wrapper) > 0) {
            return R.error();
        }

        String rawPassword= user.getPassword();
        String encPassword = passwordEncoder.encode(rawPassword);
        user.setPassword(encPassword);

        // 3. 保存用户（密码明文 → 生产请 BCrypt）
        System.out.println("用户注册：" + user);
        user.setPhone(phone);
        user.setPassword(password);   // 生产环境：BCryptPasswordEncoder.encode()
//        user.setUserName("用户" + phone.substring(7));
        user.setUpdateTime(LocalDateTime.now());
        user.setStatus(1);
        user.setUserType("0");

        userService.save(user);

        // 4. 删除验证码
        stringRedisTemplate.delete("sms:code:" + user.getPhone());
        return R.ok().data("user", user);
    }
}